﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace CUMTConnect
{
	class HTTPRequest
	{
		/**
		 * Send a request that use get method
		 * all the args shoule be provided as Dictionary and map String -> String
		 * the url shoule contain protocol 
		 */
		public static String Get(String url, Dictionary<String, String> dic)
		{
			String res = "";

			// construct a Get Request url
			StringBuilder builder = new StringBuilder();
			builder.Append(url);
			if(dic.Count > 0)
			{
				builder.Append("?");
				int i = 0;
				foreach(var item in dic)
				{
					if(i > 0)
					{
						builder.Append("&");
					}
					builder.AppendFormat("{0}={1}", item.Key, item.Value);
					i++;
				}
			}
			// request
			HttpWebRequest request = (HttpWebRequest)WebRequest.CreateHttp(builder.ToString());
			// get response
			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			// read response
			Stream stream = response.GetResponseStream();
			try
			{
				using(StreamReader reader = new StreamReader(stream, System.Text.Encoding.Default))
				{
					res = reader.ReadToEnd();
				}
			}
			finally
			{
				stream.Close();
			}
			return res;
		}
	}
}
